package tv.acgn.advertisement.servicebase.utils;

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * @author : junG
 * @program : advertisement-ad-service-base-json-utils
 * @description : JSON操作工具类 基础模块预置
 * @date : 2019-09-11 23:03
 **/
@Slf4j
public class JsonUtils {

    private static ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        //序列化的时候序列对象的所有属性
        objectMapper.setSerializationInclusion(Include.ALWAYS);
        //反序列化的时候如果多了其他属性,不抛出异常
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * Jackson 把Java对象转为Json字符串
     *
     * @param o Java对象
     *
     * @return String
     */
    public static String toJsonString(Object o) {
        try {
            return objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            log.warn("Java对象转换Json字符串失败 异常e{}", e);
        }
        return "";
    }

    /**
     * Jackson 把Java对象转为Json字符串
     *
     * @param o Java对象
     *
     * @return byte[]
     */
    public static byte[] toByteArray(Object o) {
        try {
            return objectMapper.writeValueAsBytes(o);
        } catch (JsonProcessingException e) {
            log.warn("Java对象转换Json字符数组失败 异常e{}", e);
        }
        return new byte[] {};
    }

    /**
     * 将Json字符串转换为Java对象
     *
     * @param json  Json字符串
     * @param clazz Java对象的类
     * @param <T>   返回的类泛型
     *
     * @return T
     */
    public static <T> T toJava(String json, Class clazz) {
        try {
            objectMapper.readValue(json, clazz);
        } catch (IOException e) {
            log.warn("Json字符串转换Java对象失败 异常e{}", e);
        }
        return null;
    }
}
